//
//  ViewController.swift
//  JKRegex
//
//  Created by 王冲 on 2018/1/30.
//  Copyright © 2018年 希爱欧科技有限公司. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
       
        // 匹配单个字符
        let str = "Hello, my name is Ben. Please visit my ben website at https://www.forta.com/."
        view.addSubview(label)
        label.attributedText = textRegex(str: str, font: 22)
        
    }
    
    // 1.匹配纯文本
    func textRegex(str: String,font: CGFloat) -> NSMutableAttributedString{
        
        //富文本设置
        let attributeString = NSMutableAttributedString(string:str)
        do {
            // 1.1.定义规则
            let pattern = "Ben"
            // 1.2.创建正则表达式对象
            let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options.caseInsensitive)
            // 1.3.开始匹配
            let res = regex.matches(in: str, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, str.count))

            for checkingRes in res
            {
                print("range\(checkingRes.range)")
                // substring 截取符合规定规则的qq号
                print((str as NSString).substring(with: checkingRes.range))
                //从文本checkingRes.range个字符字体HelveticaNeue-Bold
                attributeString.addAttribute(NSAttributedStringKey.font, value: UIFont(name: "HelveticaNeue-Bold", size: 22)!,range: checkingRes.range)
                //设置字体颜色
                attributeString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.blue,range: checkingRes.range)
                //设置文字背景颜色
                attributeString.addAttribute(NSAttributedStringKey.backgroundColor, value: UIColor.green,range: checkingRes.range)
            }
            return attributeString

        } catch {
            
           print(error)
        }
        return attributeString
    }
    
    lazy var label: UILabel = {
        
        let label1: UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height))
        label1.font = UIFont.systemFont(ofSize: 22)
        label1.numberOfLines = 0
        label1.backgroundColor = UIColor.white
        return label1
    }()
}

